package com.example.controller;

import com.alibaba.fastjson.JSON;
import com.example.entity.Type;
import com.example.entity.vo.SearchVO;
import com.example.service.SearchService;
import com.example.util.BeanFactroy;
import com.example.util.R;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "SearchController", value = "/SearchController/*")
public class SearchController extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置字符集编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        //获取 url
        String path = request.getPathInfo();

        if ("/SearchType".equals(path)) {
            SearchArticleType(request, response);
        } else if ("/SearchByType".equals(path)) {
            SearchByType(request, response);
        }
    }

    /**
     * 根据分类查询列表
     *
     * @param request
     * @param response
     * @throws IOException
     */
    private void SearchByType(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取类别 id
        int type = Integer.parseInt(request.getParameter("typeId"));
        System.out.println(type);
        //调用 Service 层
        List<SearchVO> searchVOS = BeanFactroy.createBean(SearchService.class).listByType(type);
        //响应数据回前端
        response.getWriter().print(JSON.toJSON(R.ok().data("listByTypes", searchVOS)));
    }

    /**
     * 查询列表分类
     *
     * @param request
     * @param response
     * @throws IOException
     */
    private void SearchArticleType(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //调用 Service 层
        List<Type> types = BeanFactroy.createBean(SearchService.class).listType();
        //响应数据回前端
        response.getWriter().print(JSON.toJSON(R.ok().data("listTypes", types)));
    }
}
